package BandB.Tool.GPhoneManager.Widget.AirplaneModeSwitcher;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class AirplaneModeSettingService extends Service {

	public static final String KEY_AIRPLANE_MODE_STATE = "airplane_mode_state";
	private String TAG = AirplaneModeSettingService.class.getSimpleName();
	
	public static final String ACTION_AIRPLANE_MODE_STATE = "com.mgeek.android.airplane.state.action";
	public static final String KEY_PROCEING_STATE = "processing_state";
	
	public static final int PROCESSING_STATE_TURNING_ON = 200;
	public static final int PROCESSING_STATE_TURNING_OFF = 220;
	
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		Log.i(TAG, "*********oncreate");
		super.onCreate();
		
		
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		Log.i(TAG, "*********onStart");
		super.onStart(intent, startId);
		
		boolean isEnabled = Settings.System.getInt(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;
		
		if(isEnabled){
			
			Log.i(TAG, "airplane mode is enabled , turning off...setting 0 to system");
			Intent turningoffIntent = new Intent();
			turningoffIntent.setAction(ACTION_AIRPLANE_MODE_STATE);
			turningoffIntent.putExtra(KEY_PROCEING_STATE, PROCESSING_STATE_TURNING_OFF);
			sendBroadcast(turningoffIntent);
			
			Settings.System.putInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON, 0);
			
			
		}else{
			Log.i(TAG, "airplane mode is disabled , turning on...setting 1 to system");
			Intent turningOnIntent = new Intent();
			turningOnIntent.setAction(ACTION_AIRPLANE_MODE_STATE);
			turningOnIntent.putExtra(KEY_PROCEING_STATE, PROCESSING_STATE_TURNING_ON);
			sendBroadcast(turningOnIntent);
			
			Settings.System.putInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON, 1);
		}
		
		
		isEnabled = Settings.System.getInt(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;

		Log.i(TAG, "send intent to notify...");
		Log.i(TAG, "airplane mode isEnabled = "+isEnabled);
		Log.i(TAG, "send action = android.intent.action.SERVICE_STATE");
		
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.intent.action.SERVICE_STATE");
		intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
		
		
		// Post an intent to reload
		Intent airplaneIntent = new Intent();
//		airplaneIntent.setAction("android.intent.action.SERVICE_STATE");
		airplaneIntent.putExtra(KEY_AIRPLANE_MODE_STATE, isEnabled);
		sendBroadcast(airplaneIntent);
		
		Intent airplaneIntent2 = new Intent();
		airplaneIntent2.setAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
		sendBroadcast(airplaneIntent2);
		

	}
	
	public static final int KEY_DELAY_SEND = 0;
	
}
